<?php

namespace Biz\module\Classes\adm;

use Biz\model\activity\CouponConfig as mCouponConfig;
use Biz\model\activity\CouponRecord as mCouponRecord;
use Biz\model\theParagraph\Store;
use Biz\model\trade\Order as mOrder;
use Biz\model\trade\OrderExtend as mOrderExtend;
use Biz\model\trade\OrderGoods as mOrderGoods;
use Biz\model\trade\OrderMatching as mOrderMatching;
use Biz\model\trade\OrderPackage as mOrderPackage;
use Biz\model\trade\OrderRefund as mOrderRefund;
use Biz\module\Classes\OrderGoods as clsOrderGoods;
use Biz\module\Classes\OrderInfo as clsOrderInfo;
use Biz\pockets\constInterface\ActivityInfo;
use Biz\service\activity\MealInfo as sMealInfo;
use Biz\service\trade\ShopCourier as sShopCourier;
use Biz\tools\Amount;
use Biz\tools\OrderNo as toolOrderNo;
use Doraemon\service\User as sUser;
use Doraemon\tools\HhzEnv;

class OrderDetail
{
    public function getInfo($orderNo)
    {
        $result = [];

        //判断是否父订单
        if (toolOrderNo::isParentNo($orderNo)) {
            throw new \Exception('父订单号不支持商家查看', 0);
        }

        //获取订单信息
        $orderInfo = mOrder::getOrderInfo($orderNo);

        if (empty($orderNo) || empty($orderInfo)) {
            throw new \Exception('抱歉，该订单不存在', 0);
        }


        //查询order字段
        $fields = [
            'cover_img',
            'title',
            'goods_id',
            'sku_id',
            'sell_price',
            'buy_price',
            'buy_num',
            'goods_amount',
            'activity_allowance',
            'discount_amount',
            'coupon_amount',
            'packet_amount',
            'integral_amount',
            'shipping_amount',
            'pay_amount',
            'promo_type',
            's_coupon_vid',
            's_coupon_amount',
            'sku_desc',
            'refund_order_no',
            'meal_amount',
            'reserve_receipt_time'
        ];

        $orderGoods = mOrderGoods::getFieldsByOrderNo($orderNo, $fields);
        $refundOrderNos = array_filter(array_column($orderGoods, 'refund_order_no'), function ($v) {
            if (empty($v)) {
                return false;
            }
            return true;
        });

        $refundList = mOrderRefund::getRefundOrderList($refundOrderNos, 'adm');
        $shopDomain = HhzEnv::detectShopDomain();

        $skuExpressInfo = @clsOrderGoods::getExpressInfo($orderNo);

        foreach ($orderGoods as &$orderGood) {
            $orderGood['promo_type_desc'] = ActivityInfo::ACTIVITY_TYPES_MAPS[$orderGood['promo_type']];
            $orderGood['goods_h5_url'] = $shopDomain . 'h5_goodsDetail/?goods_id=' . $orderGood['goods_id'];
            if (empty($orderGood['refund_order_no'])) {
                $orderGood['status'] = $orderInfo['status'];
                $orderGood['status_desc'] = mOrder::$statusAdmDesc[$orderInfo['status']];
            } else {
                if (empty($refundList[$orderGood['refund_order_no']]['rights_status'])) {
                    $orderGood['status'] = $refundList[$orderGood['refund_order_no']]['status'];
                    $orderGood['status_desc'] = $refundList[$orderGood['refund_order_no']]['status_desc'];
                    $orderGood['is_rights'] = 0; //退款
                } else {
                    $orderGood['status'] = $refundList[$orderGood['refund_order_no']]['rights_status'];
                    $orderGood['status_desc'] = mOrderRefund::$rightsStatusAdmDesc[$orderGood['status']];
                    $orderGood['is_rights'] = 1; //维权
                }
            }
            $orderGood['cover_img'] = $orderGood['cover_img_thumb_url'];

            $orderGood['express_info'] = isset($skuExpressInfo[$orderGood['sku_id']]) ? $skuExpressInfo[$orderGood['sku_id']] : [];

            $orderGood['reserve_receipt_time'] = strtotime($orderGood['reserve_receipt_time']) > 0 ? $orderGood['reserve_receipt_time'] : '';
        }

        //处理数据返回
        $result['order_no'] = $orderNo;
        $result['nick'] = sUser::getUser($orderInfo['uid'])['nick'];
        $result['uid'] = $orderInfo['uid'];
        $result['buy_num'] = $orderInfo['buy_num'];

        //收货人
        $result['accept_info'] = [
            'consignee_address' => str_replace($orderInfo['consignee_info_address'], '', $orderInfo['consignee_address']),
            'consignee_name' => $orderInfo['consignee_name'],
            'consignee_phone' => $orderInfo['consignee_phone'],
            'consignee_info_address' => $orderInfo['consignee_info_address'],
            'message' => $orderInfo['message']
        ];


        //店铺优惠券信息
        if ($orderInfo['s_coupon_vid'] > 0) {
            $result['s_coupon_info'] = mCouponRecord::get(['title'], ['coupon_vid' => $orderInfo['s_coupon_vid']]);
        }

        //订单状态
        $result['status'] = $orderInfo['status'];
        $result['status_desc'] = mOrder::$statusAdmDesc[$orderInfo['status']];

        //物流信息
        $result['delivery_tracking'] = clsOrderInfo::getOrderDeliveryTracking($orderNo, $orderInfo);

        //积分抵扣金额
        $result['integral_amount'] = $orderInfo['integral_amount'];

        //优惠券抵扣金额
        $result['coupon_amount'] = $orderInfo['coupon_amount'];
        $result['coupon_code'] = '';
        $result['coupon_id'] = $orderInfo['coupon_id'];
        $couponId = $orderInfo['coupon_id'];
        if ($couponId) {
            $couponInfo = mCouponConfig::getCouponInfo($couponId);
            if ($couponInfo) {
                $result['coupon_code'] = $couponInfo['coupon_code'];
                $result['coupon_title'] = $couponInfo['title'];
            }
        }

        //店铺优惠券抵扣金额
        $result['s_coupon_amount'] = $orderInfo['s_coupon_amount'];

        //活动补贴
        $result['activity_allowance'] = $orderInfo['activity_allowance'];


        //套餐优惠信息
        $result['meal_id'] = $orderInfo['meal_id'];
        $result['meal_title'] = $orderInfo['meal_id'] ? sMealInfo::getMeal($orderInfo['meal_id'])['meal_title'] : '';
        $result['meal_amount'] = $orderInfo['meal_amount'];

        //订单实际付款
        $result['pay_amount'] = $orderInfo['pay_amount'];

        //运费  订单金额
        $result['shipping_amount'] = $orderInfo['shipping_amount'];
        $result['goods_amount'] = $orderInfo['goods_amount'];
        $result['packet_amount'] = $orderInfo['packet_amount'];
        $result['order_amount'] = Amount::format($result['shipping_amount'] + $result['goods_amount']);

        //商品详情
        $result['goods_info'] = $orderGoods;

        //包裹信息
        $packageInfo = mOrderPackage::getFirstPackageInfo($orderNo);

        //物流公司
        $result['courier_id'] = sShopCourier::getCourierIdByCourierName($packageInfo['express_company']);

        $result['from_source'] = $orderInfo['from_source'];

        $result['canrefund_stop_time'] = $orderInfo['canrefund_stop_time'];

        $orderExtendInfo = mOrderExtend::getByOrderNo($orderNo);
        if ($orderExtendInfo) {
            $result['is_designer'] = $orderExtendInfo['is_designer'];
            $result['designer_phone'] = $orderExtendInfo['designer_phone'];
        }


        return $result;
    }

    public function getPrintInfo($parentOrderNo)
    {
        $ordersInfo = mOrder::getPaiedOrderInfoByParentOrderNo($parentOrderNo);
        $orderNos = array_column($ordersInfo, 'order_no');
        $ordersExtend = mOrderExtend::getOrderListByOrderNos($orderNos);
        $ordersGoods = mOrderGoods::getFieldsByOrderNo($orderNos);
        $formatData = [
            'base' => NULL,
            'summary' => [
                'shipping_amount' => 0,
                'pay_amount' => 0,
                'goods_num' => 0,
                'goods_amount' => 0,
                'discounted_amount' => 0
            ],
            'goods' => []
        ];

        //获取包裹列表
        $orderPackageList = mOrderPackage::getExpressInfoList($orderNos);

        foreach ($ordersInfo as $orderInfo) {
            if (!$formatData['base']) {
                $formatData['base'] = [
                    'store_list' => Store::getStoreList(),
                    'store_info' => Store::getStoreById($ordersExtend[0]['store_id']),
                    'order_no' => $ordersInfo[0]['order_parent_no'],
                    'addtime' => $ordersInfo[0]['addtime'],
                    'designer' => $ordersExtend[0]['is_designer'] ? "设计师-" . substr($ordersExtend[0]['designer_phone'], -4) : "",
                    'consignee' => implode(" ", [
                        $ordersInfo[0]['consignee_address'],
                        $ordersInfo[0]['consignee_name'],
                        $ordersInfo[0]['consignee_phone']
                    ]),
                    'express_company' => $orderPackageList[$orderInfo['order_no']][0]['express_company'],
                    'message' => $ordersInfo[0]['message']
                ];
            }
            $formatData['summary']['shipping_amount'] = bcadd($formatData['summary']['shipping_amount'], $orderInfo['shipping_amount'], 2);
            $formatData['summary']['pay_amount'] = bcadd($formatData['summary']['pay_amount'], $orderInfo['pay_amount'], 2);
            $formatData['summary']['goods_amount'] = bcadd($formatData['summary']['goods_amount'], $orderInfo['goods_amount'], 2);
        }
        $formatData['summary']['discounted_amount'] = bcsub(bcsub($formatData['summary']['pay_amount'], $formatData['summary']['shipping_amount'], 2), $formatData['summary']['goods_amount'], 2);
        foreach ($ordersGoods as $goods) {
            $formatData['goods'][] = $goods;
            $formatData['summary']['goods_num'] = $formatData['summary']['goods_num'] + $goods['buy_num'];
        }
        return $formatData;
    }


    public function getConsignee($orderNo)
    {
        $orderInfo = mOrder::getOrderInfo($orderNo);

        if (empty($orderInfo))
            return false;

        $orderMatching = mOrderMatching::getOneInfo($orderNo);

        return [
            'consignee_name' => $orderInfo['consignee_name'],
            'consignee_phone' => $orderInfo['consignee_phone'],
            'consignee_address' => $orderInfo['consignee_address'],
            'address_tipinfo' => $orderMatching['receipt_tipinfo_desc']
        ];
    }
}
